<template>
    <div class="pt-4 rounded">
        <ul>
            <li v-for="item in filteredMenu" :key="item.title" class="mb-1 text-sm">
                <div class="flex items-center cursor-pointer pt-2 pb-2 hover:bg-gray-100 rounded font-semibold"
                    :class="{ 'bg-[#F2F2F2]': selectedItem === item.title }" @click="toggle(item)">
                    <!-- 图标靠最左 -->
                    <span class="w-2 mr-2 flex-shrink-0 text-gray-700 ml-[5px]">
                        <img :src="downIcon" :class="{ 'rotate-270': !item.open }"
                            v-if="item.children && item.children.length" />
                    </span>
                    <span class="w-4 mr-2 flex-shrink-0 text-gray-700">
                        <img :src="item.icon" />
                    </span>
                    <!-- 文本也靠左 -->
                    <span class="text-left flex-1 text-[#323232]">{{ item.title }}</span>
                </div>

                <!-- 子菜单 -->
                <ul v-if="item.open && item.children && item.children.length" class="pl-6 mt-1 text-[#323232]">
                    <li v-for="child in item.children" :key="child.title"
                        class="pl-6 cursor-pointer hover:bg-gray-100 rounded text-sm h-[33px] mt-[5px] mb-[5px] flex items-center"
                        :class="{
                            'bg-[#F6F7F8] font-semibold': selectedItemChild === child.title,
                            'font-medium': selectedItemChild !== child.title,
                        }" @click="() => {
                            pushUrl(child)
                            selectedItemChild = child.title
                            selectedItem = item.title
                        }">
                        {{ child.title }}
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</template>

<script>
import { reactive, ref, watch, onMounted } from 'vue'
import downIcon from '../../assets/icons/down.svg'
import userIcon from '../../assets/icons/user.svg'
import projectIcon from '../../assets/icons/project.svg'
import { useRoute, useRouter } from 'vue-router'
import { routePermissions } from "../../utils/permission"
import { getUserRole } from '../../api/user';

export default {
    name: 'MenuComponent',
    setup(props) {
        const route = useRoute()
        const router = useRouter()

        // 菜单数据
        const menu = reactive([
            {
                title: '用户管理',
                icon: userIcon,
                open: false,
                url: '/user',
            },
            {
                title: '角色管理',
                icon: userIcon,
                open: false,
                url: '/role',
            },
            {
                title: '工艺管理',
                icon: userIcon,
                open: false,
                url: '/process',
            },
            {
                title: '工序管理',
                icon: userIcon,
                open: false,
                url: '/produce',
            },
            {
                title: '标识管理',
                icon: userIcon,
                open: false,
                url: '/identify',
                children: [
                    {
                        title: '品类管理',
                        icon: userIcon,
                        open: false,
                        url: '/identify/category',
                    },
                    {
                        title: '赋码规则',
                        icon: userIcon,
                        open: false,
                        url: '/identify/rule',
                    },
                    {
                        title: '赋码设备',
                        icon: userIcon,
                        open: false,
                        url: '/identify/device',
                    },
                    {
                        title: '仓库设置',
                        icon: userIcon,
                        open: false,
                        url: '/identify/warehouse',
                    }
                ],
            },
            {
                title: '任务管理',
                icon: userIcon,
                open: false,
                url: '/task',
            },
            {
                title: '服务管理',
                icon: userIcon,
                open: false,
                url: '/service',
            },
            {
                title: '标识溯源',
                icon: userIcon,
                open: false,
                url: '/detailinfo',
            },
        ])

        // 状态管理
        const selectedItemChild = ref(null)
        const selectedItem = ref(null)

        // 监听路由变化
        watch(
            () => route.path,
            (newPath) => {
                const m = findMenuPath(menu, newPath)
                if (m && m.child) {
                    selectedItem.value = m.parent ? m.parent.title : ''
                    selectedItemChild.value = m.child.title

                    // 如果有父菜单，设置为打开状态
                    if (m.parent) {
                        m.parent.open = true
                    }
                }
            }
        )

        // 查找菜单路径
        const findMenuPath = (menu, path) => {
            for (const parent of menu) {
                if (parent.url === path) {
                    return { parent, child: parent }
                }

                if (parent.children) {
                    for (const child of parent.children) {
                        if (child.url === path) {
                            return { parent, child }
                        }
                    }
                }
            }
            return null
        }

        // 初始化默认打开的菜单
        const openDefault = (item, path, name) => {
            for (const i in item) {
                if (item[i].children) {
                    for (const j in item[i].children) {
                        if (
                            item[i].children[j].url === path ||
                            (name && item[i].children[j].name === name)
                        ) {
                            item[i].open = true
                            selectedItem.value = item[i].title
                            selectedItemChild.value = item[i].children[j].title
                        }
                    }
                } else if (item[i].url === path || (name && item[i].name === name)) {
                    // 处理没有子菜单的菜单项
                    selectedItem.value = item[i].title
                    selectedItemChild.value = null
                }
            }
        }

        // 切换菜单展开/折叠
        const toggle = (item) => {
            if (item.children) {
                item.open = !item.open
            } else if (item.url) {
                // 没有子菜单的项点击直接导航
                pushUrl(item)
                selectedItem.value = item.title
                selectedItemChild.value = null
            }
        }

        // 导航到指定URL
        const pushUrl = (item) => {
            if (item.url) {
                router.push(item.url)
            }
        }

        // 初始化
        openDefault(menu, route.path, typeof route.name === 'string' ? route.name : undefined)

        const filteredMenu = ref([])
        const menuList = ref([])

        onMounted(async () => {
            menuList.value = JSON.parse(JSON.stringify(menu));
            // 用接口获取角色
            const userRole = await getUserRole();
            if (userRole === null) {
                router.push('/login');
                return;
            }

            filteredMenu.value = menuList.value.filter(menuItem => {
                if (menuItem.children && menuItem.children.length) {
                    const filteredChildren = menuItem.children.filter(child =>
                        routePermissions[child.url]?.includes(userRole)
                    );
                    if (filteredChildren.length > 0) {
                        menuItem.children = filteredChildren;
                        return true;
                    }
                    return false;
                }
                return routePermissions[menuItem.url]?.includes(userRole);
            });

            openDefault(filteredMenu.value, route.path, typeof route.name === 'string' ? route.name : undefined);
        })
        return {
            menu,
            downIcon,
            selectedItem,
            selectedItemChild,
            filteredMenu,
            toggle,
            pushUrl,
        }

    }

}

</script>
